package com.easipass.business.aop;

import com.easipass.commons.lang.text.JsonUtils;
import com.easipass.commons.servlet.util.RequestUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@Component
@Aspect
@Slf4j
public class BusinessAspect {

    @Autowired
    HttpServletRequest request;

    @Pointcut("execution(* springfox.documentation..*.*(..))")
    public void swagger() {}

    @Pointcut("(within(@org.springframework.web.bind.annotation.RestController *) " +
            " || within(@org.springframework.stereotype.Controller *)) && " +
            "execution(* com.easipass.business.controller.authentication.*.*(..))")
    public void businessAuthenticationPointcut() {}

    @Around("businessAuthenticationPointcut()")
    public Object allAuthenticationAround(ProceedingJoinPoint point) throws Throwable {
        Object[] objects = point.getArgs();
        this.requestPreHandle(request , objects);
        return point.proceed(objects);
    }

    @AfterReturning(returning = "rvt",
            pointcut = "(within(@org.springframework.web.bind.annotation.RestController *)"+
            " || within(@org.springframework.stereotype.Controller *))")
    public Object afterExec(JoinPoint joinPoint, Object rvt) {
        log.info("--- AfterReturningResult: "+ JsonUtils.beanToJson(rvt));
        return rvt;
    }

    private void requestPreHandle(HttpServletRequest request , Object[] objects){
        log.info("--- RequestParams: " + RequestUtils.showParams(request).toJSONString());
        Map<String, Object> requestBody = RequestUtils.showBody(request , objects);
        if(null != request.getAttribute("requestBody")){
            log.info("--- RequestBody: " + JsonUtils.beanToJson(requestBody));
        }
    }

}
